package com.saml.demo.sp.utils;

import com.alibaba.fastjson.JSON;
import lombok.extern.log4j.Log4j;
import net.shibboleth.utilities.java.support.component.ComponentInitializationException;
import net.shibboleth.utilities.java.support.xml.BasicParserPool;
import org.opensaml.messaging.decoder.MessageDecodingException;
import org.opensaml.saml.common.SAMLObject;
import org.opensaml.saml.saml2.binding.decoding.impl.HTTPPostDecoder;
import org.opensaml.saml.saml2.binding.decoding.impl.HTTPRedirectDeflateDecoder;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by Derry Luo on 2019/5/7.
 */
@Log4j
public class IDPMessageDecoder {

    public static SAMLObject decode(HttpServletRequest request) throws Exception {


        log.info("【get idp response】" + JSON.toJSONString(request.getParameterMap()));

        HTTPPostDecoder decoder = new HTTPPostDecoder();

        decoder.setHttpServletRequest(request);

        try {
            BasicParserPool parserPool = new BasicParserPool();
            parserPool.initialize();
            decoder.setParserPool(parserPool);
            decoder.initialize();
            decoder.decode();
        } catch (MessageDecodingException e) {
            throw new RuntimeException(e);
        } catch (ComponentInitializationException e) {
            throw new RuntimeException(e);
        }

//        Response response = (Response) decoder.getMessageContext().getMessage();
        SAMLObject samlObject = decoder.getMessageContext().getMessage();

        //OpenSAMLUtils.logSAMLObject(samlObject);

        return samlObject;
    }

    public static SAMLObject httpRedirectDeflateDecoder(HttpServletRequest request) throws Exception {


        log.info("【get idp response】" + JSON.toJSONString(request.getParameterMap()));

        HTTPRedirectDeflateDecoder decoder = new HTTPRedirectDeflateDecoder();

        decoder.setHttpServletRequest(request);

        try {
            BasicParserPool parserPool = new BasicParserPool();
            parserPool.initialize();
            decoder.setParserPool(parserPool);
            decoder.initialize();
            decoder.decode();
        } catch (MessageDecodingException e) {
            throw new RuntimeException(e);
        } catch (ComponentInitializationException e) {
            throw new RuntimeException(e);
        }

//        Response response = (Response) decoder.getMessageContext().getMessage();
        SAMLObject samlObject = decoder.getMessageContext().getMessage();

        //OpenSAMLUtils.logSAMLObject(samlObject);

        return samlObject;
    }

}
